// 路由白名单
const whiteList = ['/login', '/404', '/403'];
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Layout from '@/layout/index.vue';
import { useUserStore } from '@/store/modules/user';
import { usePermissionStore } from '@/store/modules/permission'; // 1. 导入 permission store

// (这些导出的路由配置现在被 permission.js 使用)
export const constantRoutes = [
  { path: '/login', name: 'Login', component: () => import('@/views/login/index.vue'), meta: { hidden: true } },
  { path: '/404', name: 'NotFound', component: () => import('@/views/error/404.vue'), meta: { hidden: true } },
  { path: '/403', name: 'Forbidden', component: () => import('@/views/error/403.vue'), meta: { hidden: true } },
];

export const asyncRoutes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: 'home', name: 'Home', component: () => import('@/views/home/index.vue'), meta: { title: '首页', icon: 'House', roles: ['0','2'] } },
      { path: 'user', name: 'UserManagement', component: () => import('@/views/user/index.vue'), meta: { title: '用户管理', icon: 'User', roles: ['0'], description: '管理系统用户信息' } },
      { path: 'category', name: 'CategoryManagement', component: () => import('@/views/category/index.vue'), meta: { title: '类型管理', icon: 'Grid', roles: ['0'], description: '管理题目分类信息' } },
      { path: 'question', name: 'QuestionManagement', component: () => import('@/views/question/index.vue'), meta: { title: '题目管理', icon: 'Tickets', roles: ['0','2'], description: '管理练习题目内容' } },
    ],
  },
  // 捕获所有未匹配的路由，重定向到404
  { path: '/:pathMatch(.*)*', redirect: '/404', meta: { hidden: true } },
];

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
});


router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    const permissionStore = usePermissionStore();

    if (userStore.token) { // 有 token
        if (to.path === '/login') {
            next({ path: '/' });
            return;
        }
        const role = userStore.userInfo && userStore.userInfo.userRole;
        // 普通用户没有权限访问其他页面
        if (role === '1' && !whiteList.includes(to.path)) {
            next('/403');
            return;
        }
        const hasRoles = role;
        if (hasRoles) {
            // 如果已经有用户信息，并且 permission store 已经计算过路由，直接放行
            if (permissionStore.routes.length > 0) {
                next();
            } else {
                // 这是刷新页面后的情况，重新生成路由
                try {
                    const accessedRoutes = permissionStore.generateRoutes(role);
                    accessedRoutes.forEach(route => router.addRoute(route));
                    next({ ...to, replace: true });
                } catch (error) {
                    await userStore.logout();
                    next('/login');
                }
            }
        } else { // 没有用户信息，需要去获取
            try {
                await userStore.fetchUserInfo();
                const accessedRoutes = permissionStore.generateRoutes(userStore.userInfo.userRole);
                accessedRoutes.forEach(route => router.addRoute(route));
                // 确保动态路由添加完毕后，再进行重定向
                next({ ...to, replace: true });
            } catch (error) {
                await userStore.logout();
                next('/login');
            }
        }
    } else { // 没有 token
        if (to.path === '/login') {
            next();
        } else {
            next('/login');
        }
    }
});


export default router;